import { GetterTree, MutationTree, ActionTree } from 'vuex';
import { LoginState } from './login.interface';
import Http, { Api } from '@/request';

const state: LoginState = {
  username: '',
  password: ''
};

// 强制使用getter获取state
const getters: GetterTree<LoginState, any> = {
  username(states): string {
    return states.username;
  },
  password(states): string {
    return states.password;
  }
};

// 更改state
const mutations: MutationTree<LoginState> = {
  // 更新state都用该方法
  LOGIN_IN(states: any, payload: LoginState) {
    states.username = payload.username;
    states.password = payload.password;
  }
};

const actions: ActionTree<LoginState, any> = {
  login({ commit }, data: LoginState) {
    return new Promise((resolve, reject) => {
      Http.post(Api.LOGIN, data)
        .then(res => {
          console.log('login===>>>', Api.LOGIN);
          // 修改数据状态  当然 在登录接口可能用不到
          commit('LOGIN_IN', data);
          // 只返回数据
          resolve(res);
        })
        .catch(() => {
          reject();
        });
    });
  }
};

export default {
  state,
  getters,
  mutations,
  actions
};
